package org.visionlibrary.image.filters.effects;

import java.util.Random;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class Jitter extends AbstractFilter {
	protected int amount = 10;

	public Jitter() {
		this(10);
	}

	public Jitter(int amount) {
		this.amount = amount;
	}

	public int getAmount() {
		return amount;
	}

	public void setAmount(int amount) {
		this.amount = amount;
	}

	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);
		
		int maxX = src.getWidth();
		int maxY = src.getHeight();

		Random random = new Random();

		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				float xfactor = random.nextFloat();
				float yfactor = random.nextFloat();

				int xcord = Math.abs(x + (int) ((xfactor - 0.5) * amount));
				int ycord = Math.abs(y + (int) ((yfactor - 0.5) * amount));

				// to avoid nullpointerexception
				if (xcord >= maxX)
					xcord = maxX - 1;

				if (ycord >= maxY)
					ycord = maxY - 1;

				// we use the same xfactor, yfactor, xcord and ycord
				// for every image channel
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					int newPixelVal = src.getSample(xcord, ycord, ch);
					dest.setSample(x, y, ch, newPixelVal);
				}
			}

		return dest;
	}
}
